/**
 * 
 */
package com.effectiv.req1.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.effectiv.req1.domain.Company;
import com.effectiv.req1.domain.Project;
import com.effectiv.req1.domain.User;

import com.effectiv.req1.repository.ProjectRepository;

import com.effectiv.req1.security.SecurityUtil;

/**
 * @author Dhrubo
 * 
 */
@Controller
@Slf4j
public class ProjectController {

	@Autowired
	private ProjectRepository projectRepository;

	@RequestMapping(value = "/newproject")
	public final String showHome(Model model) {
		Project project = new Project();

		model.addAttribute(project);

		return "newproject";
	}

	@RequestMapping(value = "/editproject")
	public final String editProject(@RequestParam("project") String id,
			Model model) {
		Project project = projectRepository.findOne(id);

		model.addAttribute(project);

		return "editproject";
	}

	@RequestMapping(value = "/listprojects")
	public final String showProjects(Model model) {
		Company company = SecurityUtil.getUserDetails().getCompany();

		List<Project> projects = null;

		if (SecurityUtil.isCompanyAdmin()) {
			// show all the projects for the company
			log.info("Find by company");
			projects = projectRepository.findByCompany(company);
		} else {
			// normal user show all the projects where he is a participant
			log.info("Find by company and user");
			projects = projectRepository.findByCompanyAndUsers(company,
					SecurityUtil.getUserDetails());
		}

		log.info("projects == {}", projects);

		model.addAttribute("projects", projects);

		return "listprojects";
	}

	@RequestMapping(value = "/saveproject", method = RequestMethod.POST)
	public final String saveproject(@Valid Project project, BindingResult result) {
		log.info("result = {}", result);

		if (!result.hasErrors()) {
			Date timestamp = new Date();

			project.setCreatedDate(timestamp);
			project.setLastUpdatedDate(timestamp);

			project.setCreatedBy(SecurityUtil.getUserDetails());
			project.setLastUpdatedBy(SecurityUtil.getUserDetails());
			project.setCompany(SecurityUtil.getUserDetails().getCompany());
			
			List<User> users = new ArrayList<User>();
			users.add(SecurityUtil.getUserDetails());

			projectRepository.save(project);
		}

		return "newproject";
	}

}
